<?php
// +----------------------------------------------------------------------
// | my [负责builder的处理]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: $this <498944516.qq.com>
//  
// +----------------------------------------------------------------------


/**
 * 处理搜索相关
 * @return 
 * @author  $this <498944516@qq.com>
 * 《你好，2017》
 * 秋日红叶暖，
 * 黎黄楼顶，沐浴斜阳，望江滩。
 * 天道大秦，岂畏难？
 * 三年弹指，然一挥之间。
 *
 * 冬雪梧桐染，
 * 常青五院，共谱春秋，写长港。
 * 夫妻同心，斩荆棘！
 * 蓦然回首，当一马平川。
 * 
 */

function my_map($param=[]) {
   
        //基本map
        $map=$like = $in=$do = array();
        if (!is_admin(session('id'))) $map['aid']=session('aid');
        $map['status']=['EGT',0];

        if ( isset($param['like']) ) {
            $like = $param['like'];
            unset($param['like']);
        }
        if ( isset($param['in']) ) {
            $in = $param['in'];
            unset($param['in']);
        }
        if ( isset($param['do']) ) {
            foreach ($param['do'] as $key => $do) {
                unset($param[$do]);
            }
            unset($param['do']);
        }

        if ( isset($param["create_time_start"]) ) {
             if (!isset($param["create_time_end"]))$param["create_time_end"]=time();
            $map['create_time']=['between time',[$param["create_time_start"],$param["create_time_end"]]];
            unset($param["create_time_start"]);
            unset($param["create_time_end"]);
        }
        if(is_array($param)){
           
            foreach ( $param as $key => $value ) {
                if ($value==='')continue;
                $key = str_replace(['[', ']'], ['', ''], $key);
                if ( in_array($key, $like) ) {
                    $map[$key] = ['like', '%'.$value.'%'];
                } else if ( in_array($key, $in) ) {
                    $map[$key] = ['in', $value];
                } else {
                    $map[$key] = $value;
                    if (strstr($value,'>'))$map[$key] = ['gt',str_replace('>','',$value)];

                    
                }
            }
        }

    

    
    return $map;
}

/**
 * 根据搜索条件获取结果数据
 * @return boolean true-管理员，false-非管理员
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function my_data($model,$where=[],$data=[])
{
    $field=isset($data['field'])?$data['field']:true;
    $order=isset($data['order'])?$data['order']:'id desc';
    $group_order=isset($data['group_order'])?$data['group_order']:'';
    $group=isset($data['group'])?$data['group']:'';
    $debug=isset($data['debug'])?$data['debug']:0;
   
   
    //第一步，准备缓存这个页面的查询条件
    $this_page=request()->controller().request()->action()."_map";
    $param=session($this_page);
    if (input('post.')){
      $param =input('post.');
      session($this_page,$param);
      $page=1;
      input('get.page',1);
    }else{
      $page=input('get.page');
    }
    if (!$param)$param=[];
  
    //处理掉关键字段
    foreach ($param as $key => $value) {
         if ($value==='') unset($param[$key]);
    }

    $group_sum=$group_count='';
    $bases=['limit','group','field','group_sum','group_count','order','sum','count'];
    foreach ($bases as $key => $base) {
      if(isset($param[$base])) {
       $$base=$param[$base];
       unset($param[$base]); 
      }
    }
    if (!isset($limit))$limit=20;
    
 
   //获取搜索条件
    $map=my_map($param);
    if ($where)$map=array_merge ($where,$map); 
  
   
    //统计
    $table=db($model);
    
    if ($group){
        $return=my_group($table,$map,$group,$group_count,$group_sum,$page,$limit,$group_order);
    }else{
         if ( isset($map['_string']) ) {
            $map_str=$map['_string'];
            unset($map['_string']);
            $return['rows'] =$table->field($field)->where($map)->where($map_str)->page($page,$limit)->order($order)->select();
            
        }else{
            $return['rows'] =$table->field($field)->where($map)->page($page,$limit)->order($order)->select();
        }
        
         // mymysql($table);
        $return['total'] = $table->where($map)->limit($page,$limit)->count();
         //分页
        $return['page_str']="Showing ".($page-1)*$limit."-".$page*$limit." of ".$return['total'];
        $list = $table->where($map)->page($page,$limit)->paginate(20,$return['total']);
        $return['page']=$list->render();
    }
   return $return;
}


function my_group($table,$map,$group,$group_count,$group_sum,$page,$limit,$group_order=''){
     
     switch ($group) {
            case 'months':
                $group_field='FROM_UNIXTIME(create_time,"%Y%m")  months';
                $group='months';
               break;
             case 'weeks':
                $group_field= ' FROM_UNIXTIME(create_time,"%Y%u") weeks';
                $group='weeks';
               break;
             case 'days':
                $group_field= 'FROM_UNIXTIME(create_time,"%Y%m%d") days';
                $group='days';
               break;
            default:
                $group_field=$group;
               break;
        }

        //处理count ,sum
        if ($group_count){
            $counts=explode(',', $group_count);
            foreach ($counts as $key => $value) {
               $group_field.=",count(".$value.") as ".$value;
            }
        }
        if ($group_sum){

            $sums=explode(',', $group_sum);
            foreach ($sums as $key => $value) {
               $group_field.=",sum(".$value.") as ".$value;
            }
        }
      
        if ( isset($map['_string']) ) {
            $map_str=$map['_string'];
            unset($map['_string']);
            $return['rows'] =$table->field($group_field)->where($map)->where($map_str)->page($page,$limit)->group($group)->order($group_order)->select();
            
        }else{
            $return['rows'] =$table->field($group_field)->where($map)->page($page,$limit)->group($group)->order($group_order)->select();
        }
       

      
        $rows_total=count($return['rows']);
        $group_arr = $table->field($group_field)->where($map)->group($group)->select();
        $return['total']=count($group_arr);

        //分页
        $return['page_str']="Showing ".($page-1)*$limit."-".$page*$limit." of ".$return['total'];
        $list = $table->where($map)->field($group_field)->group($group)->page($page,$limit)->paginate(20,$return['total']);
        $return['page']=$list->render();

        $return['group']=$group;

        return $return;

}

//合计本页特殊字段
function my_boss(){
    $heji=[];
        if (isset($count)){
           
            $counts=explode(',', $count);
            foreach ($counts as $key => $value) {
               $$value=0;
               foreach ($return['rows'] as $k => &$v) {
                   $$value+=1;
                }
               $heji[$value]=$$value; 
            }
        }
       
      
        if (isset($sum)){
            $sums=explode(',', $sum);
            foreach ($sums as $key => $value) {
               // if ($key==$return['total']) continue;
               $$value=0;
               foreach ($return['rows'] as $k => &$v) {
                  $$value+=$v[$value];
               }
               $heji[$value]=$$value; 
            }

        $return['rows'][$return['total']]=$heji;
        $return['rows'][$return['total']]['id']=isset($return['rows'][$return['total']]['id'])?"合计".$return['rows'][$return['total']]['id']:"合计";
       }

}


function my_select($db,$key='id',$value='title',$map=[]){
        if (!$map){
        $map['aid']=session('aid');
        }
        $map['status']=['EGT',0];

        $list=db($db)->field($key.','.$value)->where($map)->select();
        $list =array_column($list, $value, $key);
        return $list;
    }

function my_edit($model,$id,$default=[])
{
    if ( $id ) {
        $data = model($model)->find($id);
    } else {
        $data = $default;
    }
    return $data;
}

function my_domain(){
  // return $_SERVER['SERVER_NAME'];
  return request()->domain();
}

// 纠错级别：L、M、Q、H
// 点的大小：1到10,用于手机端4就可以了
// 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
 // 生成的文件名
function my_qrcode($data,$level = 'L', $size = 4,$path ='default'){
    vendor("phpqrcode.phpqrcode");
    
    if ($path){
        $path="uploads/qrcode/".$path;
        createFolder($path); 
        $fileName = $path.'/'.$data.'.png'; 
        \QRcode::png($data, $fileName, $level, $size);
        return $fileName;
    }else{
        $fileName =false;
        return \QRcode::png($data, $fileName, $level, $size);
    }
}

 // 获取配置
 // my_config('FEED_ROB','1111','We');
function my_config($key, $default = '', $module = '',$aid=0)
{
     
    $mod = $module ? $module : request()->module();
    $aid=session('aid');
    $table=db('Config');
    $result = cache('conf_' . strtoupper($mod) . '_' . strtoupper($key) .'_' .$aid);
    if (empty($result)) {
        $map['aid']=$aid;
        $map['name'] ='_' . strtoupper($mod) . '_' . strtoupper($key);
        $config =$table->where($map)->find();
        mymysql($table);

        if (!$config['value']) {
            $result = $default;
        } else {
            $result = $config['value'];
        }
    
     cache('conf_' . strtoupper($mod) . '_' . strtoupper($key) .'_' .$aid,$result);
    }
    
    return $result;
}

//处理表情
 function ubbReplace($str){
        $str = str_replace("<",'&lt;',$str);
        $str = str_replace(">",'&gt;',$str);
        $str = str_replace("\n",'<br/>',$str);
        $str = preg_replace("[\[/表情([0-9]*)\]]","<img src=\"/static/admin/js/plugins/qqface/face/$1.gif\" />",$str);
        return $str;
}



//导出处理
function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("phpexcel.PHPExcel");
        $objPHPExcel = new PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        
       $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
       $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));  
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 
        } 
          // Miscellaneous glyphs, UTF-8   
        for($i=0;$i<$dataNum;$i++){
          for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
          }             
        }  
        
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
        $objWriter->save('php://output'); 
        exit;   
}








